﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Configuration;
using System.IO;
using iLangl.Model;
using System.Web.Security;

namespace iLangl.Security
{
	public class MockupAuthenticationManager : BaseManager, IAuthenticationService
	{
		
		#region IAuthenticationService Members

		#region Singelton Pattern
		public MockupAuthenticationManager()
		{
			sessions = new Hashtable();
		}

		private static MockupAuthenticationManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the MockupAuthenticationService.
		/// </summary>
		public static MockupAuthenticationManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new MockupAuthenticationManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		private String StoragePath
		{
			get
			{
				String result = ConfigurationManager.AppSettings["AuthenticationConfiguration"];

				if(String.IsNullOrEmpty(result))
				{
					result  = "C:\\FileStorage\\Common\\SessionStorage.xml";
				}

				FileInfo fi = new FileInfo(result);

				if (!fi.Directory.Exists)
				{
					fi.Directory.Create();
				}
				if (!fi.Exists)
				{
					getcurrentStorage().WriteXml(fi.FullName);
				}


				return result;
			}
		}

		private dtoMockupSessionStorage _storage = null;
		private dtoMockupSessionStorage getcurrentStorage()
		{
			if (_storage == null)
			{
				_storage = new dtoMockupSessionStorage();
				_storage.ReadXml(StoragePath);
			}

			return _storage;
		}

		public dtoMockupSessionStorage Storage
		{
			get
			{
				return getcurrentStorage();
			}
		}

		public void AssignContactToUserAccount(string userAccountId, string contactId)
		{
			refreshData();
			dtoMockupSessionStorage.UserAccountsRow uar = Storage.UserAccounts.FindById(userAccountId);

			uar.ContactId = contactId;

			AcceptChanges(Storage);
		}


		public String ReadContactIdUserAccountId(string userAccountId)
		{
			refreshData();
			dtoMockupSessionStorage.UserAccountsRow uar = getcurrentStorage().UserAccounts.FindById(userAccountId);

			if (uar == null)
				return null;

			if (uar.IsContactIdNull())
				return null;

			return uar.ContactId;
		}

		
		private void refreshData()
		{
			dtoMockupSessionStorage storage = getcurrentStorage();
			if (storage != null)
			{
				storage.Clear();
				storage.ReadXml(StoragePath);
			}

		}

		static object savemutex = new object();

		private void AcceptChanges(dtoMockupSessionStorage storage)
		{
			
				storage.WriteXml(StoragePath);
		}

		Hashtable sessions;
		public string CreateSession(string login, string password)
		{
			refreshData();

			dtoMockupSessionStorage storage = getcurrentStorage();
			string userId = string.Empty;
			foreach (dtoMockupSessionStorage.UserAccountsRow cr in storage.UserAccounts)
			{
				if (cr.IsPasswordNull())
					continue;

				if (
					(string.Compare(cr.UserName.Trim(), login.Trim(), true) == 0)
					&& (string.Compare(cr.Password.Trim(), password.Trim(), true) == 0))
				{
					userId = cr.Id;
				}
			}

			if (String.IsNullOrEmpty(userId))
			{
				throw new ApplicationException("Authentication is faled!");
			}

			dtoMockupSessionStorage.SessionsRow sr = storage.Sessions.NewSessionsRow();
			sr.SessionId = Guid.NewGuid().ToString();
			sr.UserName = login;
			sr.UserId = userId;
			sr.Time = DateTime.Now;

			storage.Sessions.AddSessionsRow(sr);
			AcceptChanges(storage);
			return sr.SessionId;
		}

		public bool IsAuthenticated(string sessionKey)
		{
			refreshData();
			return (getcurrentStorage().Sessions.FindBySessionId(sessionKey) != null);
		}

		public string GetUserId(string sessionKey)
		{
			refreshData();
			dtoMockupSessionStorage.SessionsRow sr = getcurrentStorage().Sessions.FindBySessionId(sessionKey);

			if (sr == null)
				return String.Empty;

			return sr.UserId;
		}


		public String RegisterUser(string login, string password)
		{
			refreshData();
			dtoMockupSessionStorage storage = getcurrentStorage();
			dtoMockupSessionStorage.UserAccountsRow userRow = null;


			foreach (dtoMockupSessionStorage.UserAccountsRow uar in storage.UserAccounts)
			{
				if (String.Compare(login.Trim(), uar.UserName) == 0)
				{
					userRow = uar;
					break;
				}
			}

			bool isnew = (userRow == null);

			if (isnew)
			{
				userRow = storage.UserAccounts.NewUserAccountsRow();
				userRow.Id = Guid.NewGuid().ToString();
			}

			userRow.UserName = login;
			userRow.Password = password;

			if (isnew)
			{
				storage.UserAccounts.AddUserAccountsRow(userRow);
			}


			AcceptChanges(storage);

			return MembershipCreateStatus.Success.ToString();
		}

		#endregion




		public string GetUserName(string sessionKey)
		{
			throw new NotImplementedException();
		}
	}
}

